package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BankOrderStatus;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.IpayConstants;
import com.gopay.common.constants.bank.IPayOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.ipay.ebank.IpayMessage;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BankInteractRemoteService;
/**
 * 民生i支付对账
 * @CheckOrderIPayImpl.java
 * @author lilili
 * @2016年7月27日 下午5:58:28  www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderIPayImpl implements BankOrderService {

	private Logger logger = Logger.getLogger("IPAY");
    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;
    
    @Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		 CheckOrderResult checkOrderResult = new CheckOrderResult();
		 checkOrderResult.setSuccess(false);
	        checkOrderResult.setOrderId(bankOrder.getOrderId());
	        IpayMessage message = new IpayMessage();
	        message.setOrderId(bankOrder.getOrderId());
	        message.setBankOrderId(bankOrder.getOutOrderId());
	        message.setBank(BankConstants.BANK_LOGO_IPAY);
	        message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
	        message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
	        message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(),"yyyyMMddHHmmss"));//发往银行交易时间
	        message.setBank(bankOrder.getBankCode());
	        Result result = new Result();
	        try {
                if (BisBankBusinessProd._12.value.equals(bankOrder.getBankBizProdCode())) {
                    // 退款交易请求退款查询接口 add by zhengxue 20160901
                    message.setTkOriBankOrderId(bankOrder.getOriOutOrderId());
                    result = bankClient.refundQuery(message);
                    return refundCheckOrder(result, bankOrder);
                } else {
                    result = bankClient.query(message);
                }
	            
		        if (result == null || !result.isSuccess()) {
		            logger.error("bankClient fail.");
					if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
						BankCountDownLatch.failIncrease(bankOrder.getBankCode());
						checkOrderResult.setCommunicateError(true);
					}					
		            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
		            checkOrderResult.setErrMsg("系统返回对账结果为空");
		            return checkOrderResult;
		        }	
		        IpayMessage res = (IpayMessage) result.getDefaultModel();
		        if (res == null) {
		            // 查询订单为空
		            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
		            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
		            checkOrderResult.setErrMsg("银行返回对账结果为空");
		        }
		        if (!StringUtils.equals(IpayConstants.BANK_IPAY_DEAL_SUCCESS, res.getRespType())) {
		            // 查询订单错误
		            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" +  res.getRespType()+ " err: 查询订单错误");
		            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
		            checkOrderResult.setErrMsg("查询订单错误");	
		            return checkOrderResult;
		        }	
		        if(res.getRespCode()!=null && !res.getRespCode().equals("") && res.getOriRespCode()!=null && !res.getOriRespCode().equals("")){
		        // 成功处理
		        if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_SUCCESS, res.getOriRespCode())) {
		            checkOrderResult.setSuccess(true);
		            InAccInfo accInfo = new InAccInfo();
			        accInfo.setOrderId(bankOrder.getOrderId());
			        accInfo.setAmount(new BigDecimal(res.getMoneyOrder()));
			        accInfo.setRetCode("00");
			        accInfo.setCardType(BankCardType.Unknown.toString());	
			        checkOrderResult.setAccInfo(accInfo);
		            logger.error("民生i支付B2C订单" + bankOrder.getOrderId() + "的交易" + IPayOrderStatus.getName(res.getOriRespCode())+"返回码：" + res.getOriRespCode());		            
		        }
		        //失败处理
		        else if(StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_FAIL, res.getOriRespCode())){
		        	checkOrderResult.setBankFailure(true);
		            logger.error("民生i支付B2C订单" + bankOrder.getOrderId() + "的交易" + IPayOrderStatus.getName(res.getOriRespCode())+"返回码：" + res.getOriRespCode());
		            String errMsg = IPayOrderStatus.getName(res.getOriRespCode());
		            if (errMsg != null) {
		                checkOrderResult.setErrMsg(errMsg);
		            } else {
		                checkOrderResult.setErrMsg("银行返回交易失败");
		            }
		        }
		        else {
		        	 // 银行订单状态为处理中
		            logger.error("民生i支付B2C订单" + bankOrder.getOrderId() + "的交易其他状态" +"返回码：" + res.getOriRespCode());
		            String errMsg = res.getOriRespMsg();
		            if (errMsg != null) {
		                checkOrderResult.setErrMsg(errMsg);
		            } else {
		                checkOrderResult.setErrMsg("银行返回交易处理中");
		            }
		        }
		       
		        }
		        // 没有查到订单
				else {
					logger.error(" IPAY B2C orderId:" + bankOrder.getOrderId()+ ",returnMsg:  not found order");
					checkOrderResult.setErrMsg("银行返回订单未查到");
				}
			    return checkOrderResult;
	        } catch (Exception e) {
	            logger.error("bankClient fail.", e);
	            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
	            checkOrderResult.setErrMsg("银行对账异常");
	            return checkOrderResult;
	        }
	}
    
    // 退款返回处理 add by zhengxue 20160909
    public CheckOrderResult refundCheckOrder(Result result, BankOrder bankOrder) {
        CheckOrderResult checkOrderResult = new CheckOrderResult();
        checkOrderResult.setSuccess(false);
        if (result == null || !result.isSuccess()) {
            logger.error("refund bankClient fail.");
            if (result == null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())) {
                BankCountDownLatch.failIncrease(bankOrder.getBankCode());
                checkOrderResult.setCommunicateError(true);
            }
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("系统返回对账结果为空");
            return checkOrderResult;
        }
        IpayMessage res = (IpayMessage) result.getDefaultModel();
        if (res == null) {
            // 查询订单为空
            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062
                    + " err:bis query is null.");
            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
            checkOrderResult.setErrMsg("银行返回对账结果为空");
            return checkOrderResult;
        }
        if (!StringUtils.equals(IpayConstants.BANK_IPAY_DEAL_SUCCESS, res.getRespType())) {
        	 // 查询订单不存在
        	if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_NOT_EXISTENT, res.getRespCode())) {
        		
        		if(bankOrder.getOrderStatus().equals(BankOrderStatus.ACCEPTED)){
        			  //订单为已受理状态时，不允许修改
        			  logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易不存在" + "返回码：" + res.getOriRespCode());
                      checkOrderResult.setErrMsg("订单为已受理状态，未发往银行，请耐心等待");
        		}
        		else{
	                logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易不存在" + "返回码：" + res.getOriRespCode());
	                String errMsg = res.getRespMsg();
	                if (errMsg != null) {
	                    checkOrderResult.setErrMsg(errMsg);
	                } else {
	                    checkOrderResult.setErrMsg("银行返回交易处理中");
	                }
	                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
        		}
            } else{
            	 logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + res.getRespType() + " err: 查询订单错误");
                 checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
                 checkOrderResult.setErrMsg("查询订单错误");
            }
           
            return checkOrderResult;
        }
        if (res.getRespCode() != null && !res.getRespCode().equals("") && res.getOriRespCode() != null
                && !res.getOriRespCode().equals("")) {
            // 成功处理
            if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_SUCCESS, res.getOriRespCode())) {
                checkOrderResult.setSuccess(true);
                InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(bankOrder.getOrderId());
                accInfo.setAmount(new BigDecimal(res.getMoneyOrder()));
                accInfo.setRetCode("00");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
                logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易"
                        + IPayOrderStatus.getName(res.getOriRespCode()) + "返回码：" + res.getOriRespCode());
            }
            // 退款进行中
            else if (StringUtils.equals(IpayConstants.TRAN_IPAY_DEAL_TIMEOUT, res.getOriRespCode())
                    || StringUtils.equals(IpayConstants.TRAN_IPAY_DEALING, res.getOriRespCode())) {
                logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易进行中" + "返回码：" + res.getOriRespCode());
                String errMsg = res.getOriRespMsg();
                if (errMsg != null) {
                    checkOrderResult.setErrMsg(errMsg);
                } else {
                    checkOrderResult.setErrMsg("银行返回交易处理中");
                }
            } 
            //退款订单查询不存在
            else if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_NOT_EXISTENT, res.getOriRespCode())) {
            	if(bankOrder.getOrderStatus().equals(BankOrderStatus.ACCEPTED)){
      			  //订单为已受理状态时，不允许修改
            		logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易不存在" + "返回码：" + res.getOriRespCode());
            		checkOrderResult.setErrMsg("订单为已受理状态，未发往银行，请耐心等待");
	      		}
	      		else{
	                logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易不存在" + "返回码：" + res.getOriRespCode());
	                String errMsg = res.getOriRespMsg();
	                if (errMsg != null) {
	                    checkOrderResult.setErrMsg(errMsg);
	                } else {
	                    checkOrderResult.setErrMsg("银行返回交易处理中");
	                }
	                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5041);
	      		}
            } 
            else {
                // 失败处理
                checkOrderResult.setBankFailure(true);
                InAccInfo accInfo = new InAccInfo();
                accInfo.setOrderId(bankOrder.getOrderId());
                accInfo.setAmount(new BigDecimal(res.getMoneyOrder()));
                accInfo.setRetCode("01");
                accInfo.setCardType(BankCardType.Unknown.toString());
                checkOrderResult.setAccInfo(accInfo);
                logger.error("民生i支付refund订单" + bankOrder.getOrderId() + "的交易"
                        + IPayOrderStatus.getName(res.getOriRespCode()) + "返回码：" + res.getOriRespCode());
                String errMsg = IPayOrderStatus.getName(res.getOriRespCode());
                if (errMsg != null) {
                    checkOrderResult.setErrMsg(errMsg);
                } else {
                    checkOrderResult.setErrMsg("银行返回交易失败");
                }
            }
        }
        // 没有查到订单
        else {
            logger.error(" IPAY B2C refund orderId:" + bankOrder.getOrderId() + ",returnMsg:  not found order");
            checkOrderResult.setErrMsg("银行返回订单未查到");
        }
        return checkOrderResult;
    }

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
